package com.cjk.foundation.util;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class MD5Util {
	
	private final static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
			'A', 'B', 'C', 'D', 'E', 'F' };
	
	private final static String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

	public static String encrypt(String pwd) {
		try {
			byte[] btInput = pwd.getBytes();
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String encryptWithSalt(String salt, String pwdMd5) {
		try {
			byte[] btInput = PasswordUtil.hexStringToBytes(pwdMd5);
			byte[] btSalt = salt.getBytes();
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btSalt);
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getRandomString(int length) {
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; ++i) {
			int number = random.nextInt(62);
			sb.append(str.charAt(number));
		}
		return sb.toString();
	}
	
	public static String getParamsMD5(Map<String, Object> map, String key) {
		return encrypt((mapToSignString(map, key))).toUpperCase();
	}
	
	private static String mapToSignString(Map<String, Object> map, String key) {
		String paysign = "";
		List<String> list1 = new ArrayList<String>(map.keySet());
		Collections.sort(list1);
		for (String item : list1) {
			if (map.get(item) == "") {
				continue;
			}
			paysign += item + "=" + map.get(item) + "&";
		}
		paysign += "key=" + key;
		return paysign;
	}	

	public static void main(String arg[]) {
		System.out.println(getRandomString(32));
//		String salt = "OEKEuxdZEtqPAbHrrhEaof1jx1N2Jouu";
//		
//		String secret = "aydQ7YuME7OCFbyzRoKwVpuPqGXa5JBO";
		String password = encrypt("156060235300lehidJVwQJcKbEt9Ah7ACQzfLqhjII1");
		System.out.println(password);
//		String passwordSecret = encryptWithSalt(password, secret);
//		String passwordSecretSalt = encryptWithSalt(passwordSecret, salt);
//		System.out.println(passwordSecretSalt);
		
	}
}
